package com.ygqh.baby.controller.admin;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.ygqh.baby.constant.RedisConstant;
import com.ygqh.baby.model.CardCouponAction;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.foxinmy.weixin4j.util.StringUtil;
import com.ygqh.baby.ao.CardMode;
import com.ygqh.baby.ao.CardType;
import com.ygqh.baby.ao.Message;
import com.ygqh.baby.ao.PromotionType;
import com.ygqh.baby.ao.QueryInfo;
import com.ygqh.baby.ao.ResultSet;
import com.ygqh.baby.model.YgUserAddressModel;
import com.ygqh.baby.po.AdminUser;
import com.ygqh.baby.po.YgCardCoupon;
import com.ygqh.baby.po.YgCardCouponDetail;
import com.ygqh.baby.po.YgProduct;
import com.ygqh.baby.po.YgUser;
import com.ygqh.baby.po.YgUserAddress;
import com.ygqh.baby.redis.RedisDao;
import com.ygqh.baby.service.WxMpMessageService;
import com.ygqh.baby.service.YgCardCouponDetailService;
import com.ygqh.baby.service.YgCardCouponService;
import com.ygqh.baby.service.YgProductService;
import com.ygqh.baby.service.YgPromotionService;
import com.ygqh.baby.service.YgUserAddressService;
import com.ygqh.baby.service.YgUserService;
import com.ygqh.baby.shiro.utils.SessionUtil;
import com.ygqh.baby.utils.DateConvertUtils;
import com.ygqh.baby.utils.ExceptionUtil;

/**
 * @author admin
 */
@Controller
@RequestMapping("/admin/card")
public class CardCouponController extends BaseController<Object, java.lang.Long> {

	@Autowired
	private YgCardCouponService ygCardCouponService;
	@Autowired
	private YgProductService ygProductService;
	@Autowired
	private YgPromotionService ygPromotionService;
	@Autowired
	private YgCardCouponDetailService ygCardCouponDetailService;
	@Autowired
	private YgUserAddressService ygUserAddressService;
	@Autowired
	private YgUserService ygUserService;
	@Autowired
	private WxMpMessageService wxMpMessageService;
	@Autowired
	private RedisDao redisDao;

	@RequestMapping("edit")
	@ResponseBody
	public Message add(String card) {
		AdminUser user = SessionUtil.getCurrentUser();
		YgCardCoupon cardCoupon = JSON.parseObject(card, new TypeReference<YgCardCoupon>() {
		});
		if (cardCoupon.getStartDate() != null) {
			cardCoupon.setStartDate(DateConvertUtils.getMonthStartDate(cardCoupon.getStartDate()));
			cardCoupon.setEndDate(DateConvertUtils.getMonthEndDate(cardCoupon.getStartDate()));
		}
		if (cardCoupon.getId() != null) {
			cardCoupon.setUpdateTime(new Date());
			cardCoupon.setUpdateBy(user.getTrueName());
		} else {
			cardCoupon.setCreateBy(user.getTrueName());
			cardCoupon.setCreateTime(new Date());
		}

		if (cardCoupon.getCardMode().equals(CardMode.Goods)) {
			String[] productCodes = cardCoupon.getProductCode().split(",");
			for (String pCode : productCodes) {
				List<YgProduct> productList = ygProductService.findByProductCodes(new String[]{pCode}, PromotionType.ManZeng);
				String pId;
				if (CollectionUtils.isEmpty(productList)) {
					pId = ygPromotionService.addPromotionProduct(PromotionType.ManZeng, pCode, "cardEdit");
				} else {
					pId = productList.get(0).getId().toString();
				}
				if (pId == null) {
					return Message.error("该商品不存在", pCode);
				}
				YgCardCoupon clone = cardCoupon.clone();
				clone.setProductIds(pId);
				ygCardCouponService.saveOrUpdate(clone);
			}
		} else {
			ygCardCouponService.saveOrUpdate(cardCoupon);

		}

		return Message.success(null);
	}

	@RequestMapping("findById")
	@ResponseBody
	public Message findById(Long cardId) {
		YgCardCoupon card = ygCardCouponService.findById(cardId);
		if (card.getCardMode().equals(CardMode.Goods)) {
			YgProduct product = ygProductService.findById(Long.parseLong(card.getProductIds()));
			card.setProductCode(product.getProductCode());
		}
		return Message.success(card);
	}

	@RequestMapping("deleteCard")
	@ResponseBody
	public Message deleteCard(Long id) {
		AdminUser user = SessionUtil.getCurrentUser();
		int i = ygCardCouponService.deleteSoft(id, user.getTrueName());
		return Message.success(i);
	}

	@RequestMapping("searchCard")
	@ResponseBody
	public Map<String, Object> searchCard(String q, QueryInfo queryInfo, CardType cardType, CardMode cardMode, Date startDate, Date endDate) {
		if (startDate != null) {
			endDate = DateConvertUtils.getMonthEndDate(startDate);
		}
		ResultSet<YgCardCoupon> resultSet = ygCardCouponService.search(queryInfo, cardType, cardMode, startDate, endDate, q);
		return resultSet.toDatatables(null);
	}

	@RequestMapping("searchCardDetail")
	@ResponseBody
	public Map<String, Object> searchCardDetail(String q, QueryInfo queryInfo, CardType cardType, CardMode cardMode, Date startDate, Date endDate) {
		if (startDate != null) {
			endDate = DateConvertUtils.getMonthEndDate(startDate);
		}
		ResultSet<YgCardCouponDetail> resultSet = ygCardCouponDetailService.search(queryInfo, cardType, cardMode, startDate, endDate, q);
		return resultSet.toDatatables(null);
	}

	@RequestMapping("createCard")
	@ResponseBody
	public Message createCard(Long detailId, Long userId) {
		YgUserAddressModel address = ygUserAddressService.findDefaultUserAddress(userId, null);
		if (address == null) {
			return Message.error("该用户未设置收货地址", null);
		}
		YgUserAddress add = new YgUserAddress();
		add.setAddress(address.getAddress());
		add.setProvinceName(address.getProvinceName());
		add.setAreaName(address.getAreaName());
		add.setCityName(address.getCityName());
		add.setReceiver(address.getReceiver());
		add.setTelPhone(address.getTelPhone());
		ygCardCouponDetailService.cashCard(detailId, userId, add);
		return SUCCESS_MESSAGE;
	}

	@RequestMapping(value = "/cashCard")
	@ResponseBody
	public Message cashCard(@RequestParam Long userId, @RequestParam Long addrId,
							@RequestParam Long[] cardDetailId) {
		Message cashCard = null;
		YgUserAddress address = ygUserAddressService.findById(addrId, userId);
		for (Long detailId : cardDetailId) {
			cashCard = ygCardCouponDetailService.cashCard(detailId, userId, address);
		}

		return cashCard;
	}

	/**
	 * 未领取卡券 过期提醒
	 *
	 * @return
	 */
	@RequestMapping("/overdueReminder")
	@ResponseBody
	public Message overdueReminder() {
		List<YgCardCouponDetail> list = ygCardCouponDetailService.findByUnUsedCardCoupon();
		if (CollectionUtils.isEmpty(list)) {
			return Message.success(null);
		}
		logger.info("用户未使用的卡券数量：" + list.size());
		Map<Long, List<YgCardCouponDetail>> map = list.stream().collect(Collectors.groupingBy(YgCardCouponDetail::getUserId));
		logger.info("需要发送模板的用户数：" + map.size());
		List<Long> successUserIdList = new ArrayList<>();
		List<Long> errorUserIdList = new ArrayList<>();
		for (Map.Entry<Long, List<YgCardCouponDetail>> entry : map.entrySet()) {
			try {
				List<YgCardCouponDetail> detailList = entry.getValue();
				if (CollectionUtils.isEmpty(detailList)) {
					continue;
				}
				YgUser ygUser = ygUserService.findById(entry.getKey());
				StringBuffer title = new StringBuffer();
				title.append("您的礼物");
				for (int i = 0; i < detailList.size(); i++) {
					if (i != 0) {
						title.append("，");
					}
					title.append("【").append(detailList.get(i).getProductName()).append("】");
				}
				title.append("还没有兑换哦，购买任意商品就可把礼物一起起带回家啦，快去下单吧~~\n");
				Message message = wxMpMessageService.sendOverdueReminder(ygUser, title.toString(), "/user/card-coupon-list.html", "\n春夏商品热销中，快去选购吧~~", "壹果商城", DateConvertUtils.formatDateTime(new Date()));
				if (message.getType().equals(Message.Type.success)) {
					successUserIdList.add(entry.getKey());
				} else {
					errorUserIdList.add(entry.getKey());
				}
			} catch (Exception e) {
				e.printStackTrace();
				logger.error("未使用的卡券微信消息发送失败：" + ExceptionUtil.getExceptionMsg(e));
				errorUserIdList.add(entry.getKey());
			}
		}
		logger.info("成功发送微信消息的用户：" + successUserIdList.toString());
		logger.info("发送失败微信消息的用户：" + errorUserIdList.toString());
		return Message.success(null);
	}

	@RequestMapping("generateCardWithOrderId")
	@ResponseBody
	public Message generateCardWithOrderId(@RequestParam Long orderId, @RequestParam Long count, @RequestParam Long userId) {
		return ygCardCouponDetailService.generateCardWithOrderId(orderId, count, null, userId);
	}

	@RequestMapping("batchGenerateCardById")
	@ResponseBody
	public Message batchGenerateCardById(@RequestParam String userId, @RequestParam Long cardId) {
		String[] split = userId.split(",");
		YgCardCoupon ygCardCoupon = ygCardCouponService.findById(cardId);
		if (ygCardCoupon == null) {
			return Message.success("卡券不存在", null);
		}
		List<String> successList = new ArrayList<>();
		List<String> errorList = new ArrayList<>();
		for (String string : split) {
			if (StringUtils.isBlank(string)) {
				continue;
			}
			Message message = ygCardCouponDetailService.generateCardCoupon(Long.valueOf(string.trim()), ygCardCoupon, null, null, null);
			if (Message.isSuccess(message)) {
				successList.add(string);
			} else {
				errorList.add(string);
			}
		}
		Map<String, Object> data = new HashMap<>();
		data.put("success", successList);
		data.put("error", errorList);
		return Message.success(data);
	}

	private final String cardKeyPrefix = "default_card_key";

	@RequestMapping("setDefaultCard")
	@ResponseBody
	public Message setDefaultCard(@RequestParam Long cardId) {
		YgCardCoupon card = ygCardCouponService.findById(cardId);
		redisDao.hset(cardKeyPrefix, card.getCardType().name(), JSON.toJSONString(card));
		return Message.success(card);
	}

	@RequestMapping("getDefaultCard")
	@ResponseBody
	public Message getDefaultCard(CardType cardType) {
		String hget = redisDao.hget(cardKeyPrefix, cardType.name());
		YgCardCoupon card = null;
		if (StringUtil.isNotBlank(hget)) {
			card = JSON.parseObject(hget, YgCardCoupon.class);
		}
		return Message.success(card);
	}

	@RequestMapping("delDefaultCard")
	@ResponseBody
	public Message delDefaultCard(CardType cardType) {
		Long hdel = redisDao.hdel(cardKeyPrefix, cardType.name());
		return Message.success(hdel);
	}

	/**
	 * 设置卡券活动信息
	 *
	 * @param actionInfo
	 * @return
	 */
	@RequestMapping("setCardCouponAction")
	@ResponseBody
	public Message setCardCouponAction(@RequestParam String actionInfo) {
		CardCouponAction action = JSON.parseObject(actionInfo, CardCouponAction.class);
		action.setUpdateTime(new Date());
		action.setUpdateBy(getSession().getTrueName());
		CardCouponAction actionFromRedis = ygCardCouponService.getCardCouponActionInfoFromRedis();
		if (actionFromRedis != null) {
			action.setCreateBy(actionFromRedis.getCreateBy());
			action.setCreateTime(actionFromRedis.getCreateTime());
		} else {
			action.setCreateBy(action.getUpdateBy());
			action.setCreateTime(action.getUpdateTime());
		}
		redisDao.set(RedisConstant.CARD_COUPON_GIFT_ACTION, JSON.toJSONString(action), 0);
		return Message.success(null);
	}

	/**
	 * 获取卡券活动信息
	 *
	 * @return
	 */
	@RequestMapping("getCardCouponAction")
	@ResponseBody
	public Message getCardCouponAction() {
		return Message.success(ygCardCouponService.getCardCouponActionInfoFromRedis());
	}

}
